package java_file_io_nio2;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Owner
 */
public class DeleteFileFolder {

    public void deleteFile(String path) {
        File file = new File(path);
        file.delete();
    }

    public void deleteFolder(File file) {
        if (file.isDirectory()) {
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : "
                        + file.getAbsolutePath());
            } else {
                String files[] = file.list();

                for (String temp : files) {
                    File fileDelete = new File(file, temp);
                    deleteFolder(fileDelete);
                }

                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : "
                            + file.getAbsolutePath());
                }
            }

        } else {
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }

    public static void main(String args[]) {
        try {
            // saple create file
            File file = new File("d:/sample_file.txt");
            file.createNewFile();

            // sample create folder
            file = new File("d:/sample_folder");
            file.mkdir();

            for (int i = 0; i < 5; i++) {
                file = new File("d:/sample_folder/sample_file_" + i + ".txt");
                file.createNewFile();
            }

            DeleteFileFolder deleteFileFolder = new DeleteFileFolder();
            deleteFileFolder.deleteFile("D:/sample_file.txt");
            file = new File("d:/sample_folder");
            deleteFileFolder.deleteFolder(file);
        } catch (IOException ex) {
            Logger.getLogger(DeleteFileFolder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
